﻿using Coravel;
using Coravel.Invocable;

namespace JxcLite;

/// <summary>
/// 系统Web后端配置类。
/// </summary>
public static class AppWeb
{
    /// <summary>
    /// 添加系统应用程序。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="action"></param>
    public static void AddApplication(this WebApplicationBuilder builder)
    {
        Config.IsDevelopment = builder.Configuration.GetSection("IsDevelopment").Get<bool>();
#if DEBUG
        Config.IsDebug = true;
#endif
        builder.Services.AddJxcLite();
        builder.Services.AddJxcLiteCore();
        builder.Services.AddKnownWeb(option =>
        {
            option.App.WebRoot = builder.Environment.WebRootPath;
            option.App.ContentRoot = builder.Environment.ContentRootPath;
            option.Database = db =>
            {
                var connString = builder.Configuration.GetSection("ConnString").Get<string>();
                //db.AddAccess<System.Data.OleDb.OleDbFactory>(connString);
                db.AddSQLite<Microsoft.Data.Sqlite.SqliteFactory>(connString);
                //db.AddSqlServer<Microsoft.Data.SqlClient.SqlClientFactory>(connString);
                //db.AddMySql<MySqlConnector.MySqlConnectorFactory>(connString);
                //db.AddPgSql<Npgsql.NpgsqlFactory>(connString);
                //db.AddDM<Dm.DmClientFactory>(connString);
                //db.SqlMonitor = c => Console.WriteLine($"{DateTime.Now:HH:mm:ss} {c}");
            };
        });

        // 添加任务
        builder.Services.AddScheduler();
        builder.Services.AddTransient<ImportTaskJob>();
    }

    /// <summary>
    /// 使用系统Web应用程序。
    /// </summary>
    /// <param name="app"></param>
    public static void UseApplication(this WebApplication app)
    {
        //使用Known框架
        app.UseKnown();
        //配置定时任务
        app.Services.UseScheduler(scheduler =>
        {
            //每5秒执行一次异步导入
            scheduler.Schedule<ImportTaskJob>().EveryFiveSeconds();
        });
    }
}

class ImportTaskJob : IInvocable
{
    public Task Invoke() => ImportHelper.ExecuteAsync();
}